package com.redshark.wmm.MeasurementProcessing;

import android.util.Log;

public class ResistanceProcessor implements MeasurementProcessor {
	private final String TAG = "ResistanceProcessor";

	private int count = 0;
	
	private double total = 0;
	
	public static double processMeasurement(int ADReading, int channel) {
		double value = AD_CONSTANT * ADReading;

		switch (channel) {
		// 700
		case 0:
			if (value < .25) {
				value = 227.52 * value - 0.9969;
			} else {
				value = 168.66 * Math.pow(value, 4) - 688.38
						* Math.pow(value, 3) + 1189 * Math.pow(value, 2)
						- 521.65 * value + 157.35;
			}

			break;

		// 5k
		case 1:
			value = 623.1 * Math.exp(1.2528 * value);
			break;

		// 10k
		case 2:
			value = 1191.8 * Math.exp(1.284 * value);
			break;

		// 50k
		case 3:
			value = 6486.6 * Math.exp(1.2223 * value);
			break;

		// 100k
		case 4:
			value = 11312 * Math.exp(1.2991 * value);
			break;

		// 500k
		case 5:
			value = 62733 * Math.exp(1.196 * value);
			break;

		// 1M
		case 6:
			value = 125100 * Math.exp(1.164 * value);
			break;

		// 5M
		case 7:
			value = 486600 * Math.exp(1.0379 * value);
			break;

		}
		return value;
	}

	@Override
	public Measurement displayMeasurement(int[] data) {
//		 return new Measurement(data[0]*AD_CONSTANT, new
//		 DecimalFormat("###,###.###"), "MOhms Range 700");

		if(data[7]*AD_CONSTANT>3.2){
			//Clear any measurments
			count = 0;
			total = 0;
			
			//Return Internet
			return new Measurement(Double.POSITIVE_INFINITY, 3,
					"Ohms");
		}
		
		double lastDistance = Double.MAX_VALUE;
		int shortestDistance = 0;
		for (int i = 0; i < 8; i++) {
			double d = data[i] * AD_CONSTANT;
			double distanceFromMid = Math.abs(d - 1.65);
			if (distanceFromMid < lastDistance) {
				lastDistance = distanceFromMid;
				shortestDistance = i;
			}
		}

		Log.v(TAG, "Processing Range: " + shortestDistance + " Data: " + data[shortestDistance]);

		double value = processMeasurement(data[shortestDistance],
				shortestDistance);

		total += value;
		count++;

		if (count > 0) {
			double returnValue = total/count;//	 = value;
			count = 0;
			total = 0;

			if (returnValue > 1000000) {
				return new Measurement(returnValue / 1000000, 3, "MOhms");
			} else if (returnValue > 1000) {
				return new Measurement(returnValue / 1000, 3, "KOhms");
			} else {
				return new Measurement(returnValue, 3,
						"Ohms");
			}
		}
		else{
			return null;
		}

	}

}
